package 极客算法训练营.chapter03;

/**
 * 给定一个数组，将数组中的元素向右移动 k 个位置，其中 k 是非负数。
 * 示例 1:
 * <p>
 * 输入: [1,2,3,4,5,6,7] 和 k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * 向右旋转 1 步: [7,1,2,3,4,5,6]
 * 向右旋转 2 步: [6,7,1,2,3,4,5]
 * 向右旋转 3 步: [5,6,7,1,2,3,4]
 */
public class 旋转数组 {
    public static void main(String[] args) {
        int[] demo = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
        rotate(demo, 3);

    }

    public static void rotate(int[] nums, int k) {
        int j = 0, len = nums.length;
        if (k > len) {
            k = k % len;
        }
        int[] tmp = new int[k];
        for (int i = len - k; i < len; i++) {
            tmp[j++] = nums[i];
        }
        for (int i = len - k - 1; i >= 0; i--) {
            nums[i + k] = nums[i];
        }
        for (int i = 0; i < k; i++) {
            nums[i] = tmp[i];
        }
    }

    public static void rotate2(int[] nums, int k) {
        int len = nums.length;
        k = k % len;
        reverse(nums, 0, len - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, len - 1);
    }

    public static void reverse(int[] array, int start, int end) {
        int tmp = 0;
        while (start < end) {
            tmp = array[start];
            array[start] = array[end];
            array[end] = tmp;
            start++;
            end--;
        }
    }


}
